package com.ruoyi.tongban.utils;

import com.ruoyi.common.utils.StringUtils;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @Description
 * @Author caiyanshan
 * @Date 2021/4/7 10:09
 * @Param
 * @Return
 */
public class Base64ImageUtils {
  
  public static String getBase64File(String url){
    
    String encode="";
    try{
      encode = Base64.encode(download(url));
    }catch (Exception e){
    
    }
    return encode;
  }
  
  /**
   * <p>将文件转成base64 字符串</p>
   */
  public static String encodeBase64File(byte[] bytes){

    String encode="";
    try{
      encode = Base64.encode(bytes);
    }catch (Exception e){
    
    }
    return encode;
  }
  
  private static byte[] download(String url) {
    OkHttpClient client = new OkHttpClient();
    Request req = new Request.Builder().url(url).build();
    Response resp = null;
    try {
      resp = client.newCall(req).execute();
      if (resp.isSuccessful()) {
        ResponseBody body = resp.body();
        InputStream is = body.byteStream();
        return readInputStream(is);
      }
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("Unexpected code " + resp);
    }
    return null;
  }
  
  /**
   * 读取字节输入流内容
   *
   * @param is
   * @return
   */
  private static byte[] readInputStream(InputStream is) {
    ByteArrayOutputStream writer = new ByteArrayOutputStream();
    byte[] buff = new byte[1024 * 2];
    int len = 0;
    try {
      while ((len = is.read(buff)) != -1) {
        writer.write(buff, 0, len);
      }
      is.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return writer.toByteArray();
  }
  
  
  public static String saleUrl(String url){
    try {
      url = url.replaceAll("\\+","-").replaceAll("/","_").replaceAll("=","");
      url = URLEncoder.encode(url,"utf-8");
    }catch (Exception e){
    
    }
    return url;
  }
  
  public static String unSaleUrl(String url){
    try {
      url = url.replaceAll("-","\\+").replaceAll("_","/");
      //url = URLEncoder.encode(url,"utf-8");
    }catch (Exception e){
    
    }
    return url;
  }
  
}
